package com.sxm.yiwei.pinche;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.sxm.yiwei.R;
import com.sxm.yiwei.base.BaseActivity;
import com.sxm.yiwei.beans.City;
import com.sxm.yiwei.constant.Constant;
import com.sxm.yiwei.tools.DBHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class SelectPositionActivity extends BaseActivity implements View.OnClickListener,Inputtips.InputtipsListener, AMapLocationListener {

    private RelativeLayout rl_back;
    private TextView tv_city;
    private EditText et_pos;
    private TextView tv_pos;
    private TextView tv_relocate;
    private String city;
    private LinearLayout ll_locate;
    private ListView search_result;
    private ArrayList<Tip> tipList=new ArrayList<>();
    private TipAdapter tipAdapter;
    private TextView tv_noresult;
    private int locateProcess = 1; // 记录当前定位的状态 正在定位-定位成功-定位失败


    @Override
    public void setContentView() {
        setContentView(R.layout.activity_select_position);
    }

    @Override
    public void initView() {
        rl_back = (RelativeLayout)findViewById(R.id.rl_back);
        tv_city = (TextView)findViewById(R.id.tv_city);
        et_pos = (EditText)findViewById(R.id.et_pos);
        tv_pos = (TextView)findViewById(R.id.tv_pos);
        tv_relocate = (TextView)findViewById(R.id.tv_relocate);
        ll_locate = (LinearLayout)findViewById(R.id.ll_locate);
        search_result = (ListView)findViewById(R.id.search_result);
        tv_noresult = (TextView)findViewById(R.id.tv_noresult);


    }

    @Override
    public void initListener() {
        rl_back.setOnClickListener(this);
        tv_city.setOnClickListener(this);
        tv_relocate.setOnClickListener(this);
        et_pos.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString() == null || "".equals(charSequence.toString())) {
                    search_result.setVisibility(View.GONE);
                    tv_noresult.setVisibility(View.GONE);
                    ll_locate.setVisibility(View.VISIBLE);

                } else {
                    tipList.clear();
                    ll_locate.setVisibility(View.GONE);
                    setTips(charSequence.toString(),city);

                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        search_result.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                showToast(tipList.get(i).getName());
                Intent intent = new Intent();
                intent.putExtra("selected_tip",tipList.get(i));
                setResult(Constant.RESULT_CODE_PLACE,intent);
                finish();
            }
        });
    }


    @Override
    public void initData() {
        city=tv_city.getText().toString();
        tipAdapter = new TipAdapter();
        search_result.setAdapter(tipAdapter);
        tv_pos.setText("正在定位");
        initLoc();

    }
    private void setTips(String newText,String city){
        //第二个参数传入null或者“”代表在全国进行检索，否则按照传入的city进行检索
        InputtipsQuery inputquery = new InputtipsQuery(newText, city);
        inputquery.setCityLimit(true);//限制在当前城市

        Inputtips inputTips = new Inputtips(this, inputquery);
        inputTips.setInputtipsListener(this);

        inputTips.requestInputtipsAsyn();
    }

    // 获取位置信息 经纬度
    public void initLoc() {
        AMapLocationClient client = new AMapLocationClient(getActivity());
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setInterval(300000);
        client.setLocationListener(this);
        client.setLocationOption(option);
        client.startLocation();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.tv_city:
                startActivityForResult(new Intent(this,SelectCityActivity.class), Constant.REQUEST_CODE_CITY);
                break;
            case R.id.tv_relocate:
                locateProcess=1;
                initLoc();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data!=null){
            if (requestCode==Constant.REQUEST_CODE_CITY&&resultCode==Constant.RESULT_CODE_CITY){
                city = data.getStringExtra("city");
                tv_city.setText(data.getStringExtra("city"));
            }
        }

    }



    @Override
    public void onGetInputtips(List<Tip> list, int i) {
        //返回结果成功或者失败的响应码。1000为成功，其他为失败
        if (i==1000){
            showToast("成功");
            Log.d("tipList",list.toString());
            /*Tip tip = list.get(i);
            if (tip.getPoiID()==null&&tip.getPoint()==null){//该提示词不是一个真实存在的 POI，这时区域、经纬度参数都是空的，此时可根据该提示词进行POI关键词搜索

            }else if (tip.getPoiID()!=null&&tip.getPoint()==null){//该提示词是一个公交线路名称，此时用这个id进行公交线路查询。

            }else if (tip.getPoiID()!=null&&tip.getPoint()!=null){//提示词一个真实存在的POI，可直接显示在地图上。

            }*/
            tipList.addAll(list);

            if (tipList.size() <= 0) {
                tv_noresult.setVisibility(View.VISIBLE);
                search_result.setVisibility(View.GONE);
            } else {
                tv_noresult.setVisibility(View.GONE);
                search_result.setVisibility(View.VISIBLE);
                tipAdapter.notifyDataSetChanged();
            }
        }else {
            showToast("errorCode"+i);
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null
                && aMapLocation.getErrorCode() == 0) {//定位成功
            // 定位成功回调信息，设置相关消息
            // tv_location.setText(amapLocation.getCity()
            // + amapLocation.getDistrict() + amapLocation.getRoad());
            // tv_location.setVisibility(View.VISIBLE);
//			tv_location.setText(amapLocation.getCity());
//			Constant.lat = amapLocation.getLatitude();
//			Constant.lon = amapLocation.getLongitude();
//			Constant.city = amapLocation.getCity();

            city = aMapLocation.getCity();
            tv_city.setText(city);
            tv_pos.setText(city);
            locateProcess = 2; // 定位成功

        } else {
            Toast.makeText(
                    getApplicationContext(),
                    "Location ERR:"
                            + aMapLocation.getErrorCode(),
                    Toast.LENGTH_LONG).show();
            locateProcess = 3; // 定位失败
            city="";
            tv_city.setText("全国");
            tv_pos.setText("定位失败");

            return;
        }
    }

    private class TipAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return tipList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view= LayoutInflater.from(SelectPositionActivity.this).inflate(R.layout.tip_item,null);
            TextView result_text = (TextView) view.findViewById(R.id.result_text);
            Tip tip = tipList.get(i);
            result_text.setText(tip.getName());
            return view;
        }
    }
}
